#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :  app.py
@Time    :  2023/09/27
@Author  :  HDUZN
@Version :  1.0
@Contact :  hduzn@vip.qq.com
@License :  (C)Copyright 2023-2024
@Desc    :  购票模拟系统
            pip install flask, gevent, pandas
'''

from flask import Flask, render_template, request
from gevent.pywsgi import WSGIServer
import sqlite3, random, os

app = Flask(__name__)
app.secret_key = 'suibianshuruzijidekey'

# 首页，买票页面
@app.route('/', methods=['GET'])
def index():
    start_citys = get_column_value('start_city')
    end_citys = get_column_value('end_city')
    # start_citys = ['上海', '北京', '嘉善', '杭州']
    # end_citys = ['北京', '嘉善', '上海', '杭州']

    return render_template('index.html', start_citys=start_citys, end_citys=end_citys)

# 查询车票页面
@app.route('/search', methods=['POST'])
def search():
    start_city = request.form.get('start')
    end_city = request.form.get('end')
    date_str = request.form.get('date')
    
    # 根据起点、终点查询车票信息
    train_list = get_trains(start_city, end_city)
    # print(train_list)
    
    return render_template('search.html', train_list=train_list, date_str=date_str)

# 提交订单页面
@app.route('/order', methods=['POST'])
def order():
    train = request.form.get('train')
    seat = request.form.get('seat')
    name = request.form.get('name')
    date_str = request.form.get('date_str')
    
    # 根据车次、座位和乘车人姓名生成订单信息
    tuple_train = eval(train)
    # print(tuple_train)
    ticket_train = tuple_train[4] + '\n' + tuple_train[5].split('历')[0]
    seat_no = random.randint(1, 36)
    seat_info = str(seat_no) + random.choice(['A', 'B', 'C', 'D', 'F']) + '(' + seat + ')'
    if(seat == '一等座'):
        ticket_info = [ticket_train, date_str, name, seat_info, tuple_train[6]]
    if(seat == '二等座'):
        ticket_info = [ticket_train, date_str, name, seat_info, tuple_train[7]]
        
    return render_template('order.html', ticket_info=ticket_info)

# 付款页面
@app.route('/payment', methods=['POST'])
def payment():
    # payment = request.form.get('payment')
    ticket_info = request.form.get('ticket_info')
    tuple_train = eval(ticket_info)

    return render_template('result.html', ticket_info=tuple_train)

# 获取某个字段的所有值（去重）
def get_column_value(column_name):
    column_list = []

    conn = sqlite3.connect(os.path.join('.', 'static', 'db', 'ticket.db'))
    cursor = conn.cursor()

    sql = 'select distinct ' + column_name + ' from trains'
    cursor.execute(sql)
    results = cursor.fetchall()
    column_list = [result[0] for result in results]
    conn.close()

    return column_list

def get_trains(start_city, end_city):
    conn = sqlite3.connect(os.path.join('.', 'static', 'db', 'ticket.db'))
    cursor = conn.cursor()
    sql = 'select * from trains where start_city=? and end_city=?'
    cursor.execute(sql, (start_city,end_city))
    results = cursor.fetchall()
    conn.close()

    return results

if __name__ == '__main__':

    http_server = WSGIServer(('0.0.0.0', 5014), app)
    http_server.serve_forever()

